package com.blacktea.creationalpatterns.builderpattern.servce;

import com.blacktea.creationalpatterns.builderpattern.ms.UserMapper;
import com.blacktea.creationalpatterns.builderpattern.pojo.User;
import com.blacktea.creationalpatterns.builderpattern.pojo.UserEntity;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.HashMap;
import java.util.Map;

/**
 * @description:
 * @author: black tea
 * @date: 2023/3/19 19:38
 */
@Service
public class UserServiceImpl implements UserService {

    @Resource
    private UserMapper userMapper;

    @Override
    public User getUserById(int id) throws JsonProcessingException {
        // 假设从数据库中去到userEntity
        UserEntity userEntity = this.daoGetUserById(id);
        // 1. 将普通对象里的属性一个一个设置到构造者对象中
        User build = User.builder()
                .id(id)
                .username(userEntity.getUsername())
                .email(userEntity.getEmail())
                .build();

        // 2. 使用 MapStruct（推荐）
        User toUser = userMapper.toUser(userEntity);
        UserEntity toEntity = userMapper.toEntity(build);

        // 3. 使用jackson
        ObjectMapper mapper = new ObjectMapper();
        // 将构造者对象转为普通对象
        UserEntity newUserEntity = mapper.readValue(
                mapper.writeValueAsString(build),
                UserEntity.class
        );
        // 存在缺少的对象时会报错，例如现在缺少other,这种就需要自定义序列化
//        User user = mapper.convertValue(userEntity, User.class);

        // 4. BeanUtils.copyProperties()
        User user = User.builder().build();
        BeanUtils.copyProperties(userEntity, user);

        return build;
    }

    private UserEntity daoGetUserById(int id){
        UserEntity userEntity = new UserEntity();
        userEntity.setId(id);
        userEntity.setUsername("张三");
        userEntity.setEmail("xxx@xx.com");
        Map<String, Object> other = new HashMap<>();
        other.put("icon", "https://icon.png");
        userEntity.setOther(other);
        return userEntity;
    }
}
